<template>
  <div class="user-edit">
    <Drawer :title="title" v-model="visible" width="1200" :mask-closable="false">
      <Scroll :height="height">
      <div style="width: 90%;margin: 10px auto;">
        <div style="text-align: center;font-size: 20px">{{ company }}客户工程物料清单</div>
        <div style="text-align: center">日期：{{ projectParams.material_list_time }}</div>
        <div>项目部　：{{ organization.organization_name }}</div>
        <div>项目编号：{{ projectParams.project_code }}</div>
        <div>项目名称：{{ projectParams.project_name }}</div>
        <div>
          <table class="gridtable">
            <tr>
              <th>序号</th>
              <th>物料类别</th>
              <th>物料编码</th>
              <th>物料名称</th>
              <th>规格型号</th>
              <th>单位</th>
              <th>单价</th>
              <th>数量</th>
              <th>金额</th>
              <th>操作</th>
            </tr>
            <tr v-for="(item,index) in data" :key="index">
              <td style="text-align: center">{{index + 1}}<i style="display: none">{{item.id}}</i></td>
              <td style="text-align: center">{{item.type}}</td>
              <td style="text-align: center">{{item.code}}</td>
              <td>{{item.name}}</td>
              <td>{{item.stype}}</td>
              <td style="text-align: center">{{item.unit}}</td>
              <td style="text-align: right">{{item.tax_price}}</td>
              <td style="text-align: center;width: 100px">
                <Button size="small" type="primary" @click="handle_sub(index)">-</Button>
                <input type="text" v-model="item.count" style="width: 40px;text-align: center;" readonly="readonly">
                <Button size="small" type="primary" @click="handle_add(index)">+</Button>
              </td>
              <td style="text-align: right">{{(item.tax_price * item.count).toFixed(2)}}</td>
              <td style="text-align: center;width: 100px">
                <Button size="small" type="primary" @click="handle_edit_material(index)">编辑</Button>
                <Button size="small" type="error" @click="handle_del(index)">删除</Button>
              </td>
            </tr>
            <tr>
              <td style="text-align: center">#</td>
              <td style="text-align: center">合计</td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td style="text-align: right">{{ sum.toFixed(2) }}</td>
              <td></td>
            </tr>
          </table>
          <br/>
        </div>
      </div>
      </Scroll>
      <div class="demo-drawer-footer">
        <Button @click="handleCancel" style="margin-right: 36px;">确定</Button>
        <Button type="primary" @click="add" icon="md-add">新增</Button>
      </div>
    </Drawer>
    <Modal :title="subTitle" v-model="addEditVisiable" :mask-closable='false' :width="500" :styles="{top: '400px', left: '200px'}" @on-ok="handle_ok">
      <RadioGroup v-model="is_self_select" @on-change="insertType" v-if="insertOrEdit">
        <Radio label="系统物料"></Radio>
        <Radio label="自定义物料"></Radio>
      </RadioGroup>
      <div v-show="is_self==0">
        <Form ref="sysMaterialForm" :model="sysMaterialForm" :label-width="100">
          <FormItem label="物料名称" prop="sysMaterialForm.material_name" class="margin-bottom-3">
            <Select v-model="sysMaterialForm.material_name" clearable filterable style="width:320px" @on-change="changeMaterialName">
              <Option v-for="(item,index) in materialClass" :value="item.pre_code" :key="index">
                {{item.name}}
              </Option>
            </Select>
          </FormItem>
          <FormItem label="规格型号" prop="sysMaterialForm.material_type" class="margin-bottom-3">
            <Select v-model="sysMaterialForm.material_type" clearable filterable style="width:320px"  @on-change="changeMaterialId">
              <Option v-for="(item,index) in materialType" :value="item.id" :key="index">
                {{item.stype}}
              </Option>
            </Select>
          </FormItem>
          <FormItem label="含税单价" prop="sysMaterialForm.tax_price" class="margin-bottom-3">
            <InputNumber v-model="sysMaterialForm.tax_price" style="width: 320px" />
          </FormItem>
          <FormItem label="数量" prop="sysMaterialForm.count" class="margin-bottom-3">
            <InputNumber v-model="sysMaterialForm.count" style="width: 320px" />
          </FormItem>
        </Form>
      </div>
      <div v-show="is_self==1">
        <Form ref="selfMaterialForm" :model="selfMaterialForm" :label-width="100">
          <FormItem label="规格型号" prop="sysMaterialForm.type" class="margin-bottom-3">
            <Select v-model="selfMaterialForm.type" clearable filterable style="width:320px" >
              <Option value="设备" checked>设备</Option>
              <Option value="主材">主材</Option>
            </Select>
          </FormItem>
          <FormItem label="物料名称" prop="selfMaterialForm.name" class="margin-bottom-3">
            <Input v-model="selfMaterialForm.name" style="width: 320px" />
          </FormItem>
          <FormItem label="规格型号" prop="selfMaterialForm.stype" class="margin-bottom-3">
            <Input v-model="selfMaterialForm.stype" style="width: 320px" />
          </FormItem>
          <FormItem label="含税单价" prop="selfMaterialForm.tax_price" class="margin-bottom-3">
            <InputNumber v-model="selfMaterialForm.tax_price" style="width: 140px" />，重量 
            <InputNumber v-model="selfMaterialForm.weight" style="width: 110px" />kg
          </FormItem>
          <FormItem label="数量" prop="selfMaterialForm.count" class="margin-bottom-3">
            <InputNumber v-model="selfMaterialForm.count" style="width: 140px" />，单位
            <Input v-model="selfMaterialForm.unit" style="width: 110px" />
          </FormItem>
        </Form>
      </div>

    </Modal>
  </div>
</template>
<script>
import { deleteProjectMaterial, deleteProjectMaterialDefine, updateProjectMaterial, updateProjectMaterialDefine, 
         getProjectMaterial, getProjectMaterialDefine } from '@/api/project';
import { getAllMaterialName, getAllMaterials, getMaterialById } from '@/api/typical';
import { insertProjectMaterial, insertProjectMaterialDefine } from '@/api/material';
import { getStore } from '@/libs/storage';
import { material_tax_race } from '@/libs/axios';
export default {
  name: 'edit-project-material',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    data: {
      type: Array
    },
    projectParams: Object
  },
  data() {
    return {
      visible: this.value,
      title: "编辑项目物料清单",
      height: 540,
      submitLoading: false,
      company: '',
      organization: {},
      addEditVisiable: false,
      materialClass: [],
      materialLib: [],
      materialType: [],
      subTitle: '',
      is_self_select: '系统物料',
      is_self: 0,
      insertOrEdit: true,
      sysMaterialForm: {
        id: 0,
        material_name: '',
        material_type: 0,
        tax_price: 0,
        count: 1
      },
      selfMaterialForm: {
        id: 0,
        type: '设备',
        name: '',
        stype: '',
        tax_price: 0,
        count: 1
      }
    }
  },
  methods: {
    init() {
      const userInfo = JSON.parse(getStore('userInfo'));
      this.company = userInfo.compamy;
      this.organization = userInfo.organization;
      this.title = '编辑项目物料清单 - ' + this.projectParams.project_name;
      this.getMaterialInfo();
    },
    handleCancel() {
      this.visible = false;
    },
    setCurrentValue(value) {
      this.visible = value;
    },
    handle_sub(index) {
      if (this.data[index].count == 1) {
        return false;
      } else {
        this.data[index].count--;
      }
      this.change_count(index);
    },
    handle_add(index) {
      this.data[index].count++;
      this.change_count(index);
    },
    change_count(index) {
      const is_self = this.data[index].is_self;
      const id = this.data[index].id;
      const count = this.data[index].count;
      if (is_self == 0) {
        updateProjectMaterial({id, count}).then(res => {
          if (res.code === 0) {
            this.$Message.success(res.message);
          }
        })
      } else {
        updateProjectMaterialDefine({id, count}).then(res => {
          if (res.code === 0) {
            this.$Message.success(res.message);
          }
        })
      }
    },
    handle_edit_material(index) {
      this.subTitle = '编辑物料';
      this.insertOrEdit = false;
      this.is_self = this.data[index].is_self;
      if (this.is_self === 0) {
        this.sysMaterialForm.id = this.data[index].id;
        this.sysMaterialForm.material_name = this.data[index].code.substring(0, 6);
        this.sysMaterialForm.material_type = this.data[index].material_id;
        this.sysMaterialForm.tax_price = this.data[index].tax_price;
        this.materialType = this.materialLib.filter(item => item.base_code == this.sysMaterialForm.material_name);
        this.sysMaterialForm.count = this.data[index].count;
      } else {
        this.selfMaterialForm.id = this.data[index].id;
        this.selfMaterialForm.name = this.data[index].name;
        this.selfMaterialForm.stype = this.data[index].stype;
        this.selfMaterialForm.tax_price = this.data[index].tax_price;
        this.selfMaterialForm.unit = this.data[index].unit;
        this.selfMaterialForm.weight = this.data[index].weight;
        this.selfMaterialForm.count = this.data[index].count;
      }
      this.addEditVisiable = true;
    },
    handle_del(index) {
      this.$Modal.confirm({
        title: '确定删除',
        content: '确定要删除这条记录吗？',
        onOk: () => {
          const id = this.data[index].id;
          if (this.data[index].is_self == 0) {
            deleteProjectMaterial({id}).then(res => {
              if (res.code === 0) {
                this.data.splice(index, 1);
                this.$Message.info(res.message);
              }
            })
          } else {  // 删除自定义物料
            deleteProjectMaterialDefine({id}).then(res => {
              console.log(res)
              if (res.code === 0) {
                this.data.splice(index, 1);
                this.$Message.info(res.message);
              }
            })
          }
        }
      });
    },
    add() {
      this.subTitle = '新增物料';
      this.insertOrEdit = true;
      this.sysMaterialForm.material_name = '';
      this.sysMaterialForm.material_type = 0;
      this.sysMaterialForm.count = 1;
      this.selfMaterialForm.name = '';
      this.selfMaterialForm.stype = '';
      this.selfMaterialForm.unit = '';
      this.selfMaterialForm.weight = '';      
      this.selfMaterialForm.count = 1;
      this.materialType = [];
      this.addEditVisiable = true;
    },
    insertType(v) {
      if (v == '系统物料') {
        this.is_self = 0;
      } else {
        this.is_self = 1;
      }
    },
    getMaterialInfo() {
      // 获取所有的物料名称
      getAllMaterialName().then(res => {
        if (res.code === 0) {
          this.materialClass = res.data.raws;
        }
      });
      // 获取所有的物料
      getAllMaterials().then(res => {
        if (res.code === 0) {
          this.materialLib = res.data.rows;
        }
      })
    },
    changeMaterialName(value) {
      this.materialType = this.materialLib.filter(item => item.base_code == value);
    },
    changeMaterialId(value) {
      if (value) {
        getMaterialById({id: value}).then(res => {
          if (res.code === 0) {
            this.sysMaterialForm.tax_price = res.data.tax_price;
          }
        })
      }
    },
    handle_ok() {
      if (this.insertOrEdit) {  //新增
        if (this.is_self == 0 && this.sysMaterialForm.material_type > 0) {
          let params = {
            project_id: this.projectParams.project_id,
            material_id: this.sysMaterialForm.material_type,
            count: this.sysMaterialForm.count,
            tax_price: this.sysMaterialForm.tax_price
          };
          insertProjectMaterial(params).then(res => {
            if (res.code === 0) {
              this.$<essage.success(res.message);
            }
          })
        } else if (this.is_self == 1 && this.selfMaterialForm.name.trim().length > 0 && this.selfMaterialForm.stype.trim().length > 0) {
          let params = {
            project_id: this.projectParams.project_id,
            type: this.selfMaterialForm.type,
            name: this.selfMaterialForm.name,
            stype: this.selfMaterialForm.stype,
            tax_price: this.selfMaterialForm.tax_price,
            no_tax_price: (this.selfMaterialForm.tax_price/(1+material_tax_race)).toFixed(2),
            count: this.selfMaterialForm.count,
            weight: this.selfMaterialForm.weight,
            unit: this.selfMaterialForm.unit,
            is_self: 1
          }
          insertProjectMaterialDefine(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
            }
          })
        }
      } else {    //修改
        if (this.is_self == 0 && this.sysMaterialForm.material_type > 0) {
          let params = {
            id: this.sysMaterialForm.id,
            material_id: this.sysMaterialForm.material_type,
            count: this.sysMaterialForm.count,
            tax_price: this.sysMaterialForm.tax_price
          };
          updateProjectMaterial(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
            }
          });
        } else if (this.is_self == 1 && this.selfMaterialForm.name.trim().length > 0 && this.selfMaterialForm.stype.trim().length > 0) {
          let params = {
            id: this.selfMaterialForm.id,
            type: this.selfMaterialForm.type,
            name: this.selfMaterialForm.name,
            stype: this.selfMaterialForm.stype,
            tax_price: this.selfMaterialForm.tax_price,
            no_tax_price: (this.selfMaterialForm.tax_price/(1+material_tax_race)).toFixed(2),
            count: this.selfMaterialForm.count,
            weight: this.selfMaterialForm.weight,
            unit: this.selfMaterialForm.unit,
          };
          updateProjectMaterialDefine(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
            }
          })
        }
      }
      let params = {
        project_id: this.projectParams.project_id
      }
      this.getMaterialList(params);
    },
    getMaterialList(project_id) {
      getProjectMaterial(project_id).then(res => {
         if (res.code === 0) {
           this.data = res.data.raws;
          getProjectMaterialDefine(project_id).then(res => {
            if (res.code === 0 && res.data.length > 0) {
              this.data.push(...res.data);
            }
          })
         }
      })
    },
  },
  watch: {
    value(val) {
      this.setCurrentValue(val);
    },
    visible(value) {
      this.init();
      this.$emit("input", value);
      
    }
  },
  computed: {
    sum() {
      let sum = 0;
      this.data.forEach(item => {
        sum += item.count * item.tax_price;
      });
      return sum;
    }
  },
  mounted() {
    this.init();
    this.height = Number(document.documentElement.clientHeight - 100);
  }
}
</script>
<style lang="less" scoped>
.demo-drawer-footer{
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
.gridtable {
  font-family: verdana, arial, sans-serif;
  font-size: 12px;
  color: #000000;
  border-width: 1px;
  border-color: #777777;
  border-collapse: collapse;
  width: 100%;
}

.gridtable th {
  border-width: 1px;
  padding: 6px;
  border-style: solid;
  border-color: #aaaaaa;
  background-color: #dedede;
}

.gridtable td {
  border-width: 1px;
  padding: 4px;
  border-style: solid;
  border-color: #8b8b8b;
  background-color: #ffffff;
}

.margin-bottom-3 {
  margin-bottom: 16px;
}
</style>